package br.ufpe.cin.rgms.core.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.ufpe.cin.rgms.base.membro.model.Membro;
import br.ufpe.cin.rgms.core.dao.GenericDAO;
import br.ufpe.cin.rgms.util.HibernateUtil;

public abstract class GenericDaoHibernateImpl<T, PK extends Serializable>
		implements GenericDAO<T, PK> {

	private Class<T> clazz = getDomainClass();

	protected Session session = HibernateUtil.getSession();

	protected abstract Class<T> getDomainClass();

	public PK salva(T entity) {
		Transaction tx = session.beginTransaction();
		PK object = null;

		try {
			object = (PK) session.save(entity);
		} catch (HibernateException e) {
			tx.rollback();
		} finally {
			tx.commit();
		}
		return object;
	}

	public void delete(T entity) {
		Transaction tx = session.beginTransaction();

		try {
			session.delete(entity);
		} catch (HibernateException e) {
			tx.rollback();
		} finally {
			tx.commit();
		}
	}

	public T carrega(PK id) {
		return (T) session.get(clazz, id);
	}

	public void altera(T entity) {
		Transaction tx = session.beginTransaction();

		try {
			session.merge(entity);
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			tx.commit();
		}

	}

	public List<T> findAll() {
		return session.createCriteria(clazz).list();
	}
}
